package com.ganee.baselib.widget.image.transform;

import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.Shader;

import androidx.annotation.NonNull;

import com.bumptech.glide.load.engine.bitmap_recycle.BitmapPool;
import com.bumptech.glide.load.resource.bitmap.BitmapTransformation;

import java.security.MessageDigest;

/**
 * 创建日期： 2017/12/22
 * 描述：圆角矩形
 * 作者：@author eric
 */

public class GlideRoundTransform extends BitmapTransformation {

    private static float radius = 0f;

    /**
     * 构造函数 默认圆角半径 4dp
     *
     * @param context Context
     */
    public GlideRoundTransform(Context context) {
        this(8);
    }

    /**
     * 构造函数
     *
     * @param dp      圆角半径
     */
    public GlideRoundTransform(int dp) {
        super();
        radius = Resources.getSystem().getDisplayMetrics().density * dp;
    }

    @Override
    protected Bitmap transform(BitmapPool pool, Bitmap toTransform, int outWidth, int outHeight) {
        return roundCrop(pool, toTransform);
    }

    private static Bitmap roundCrop(BitmapPool pool, Bitmap source) {
        if (source == null) return null;

        Bitmap result = pool.get(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        if (result == null) {
            result = Bitmap.createBitmap(source.getWidth(), source.getHeight(), Bitmap.Config.ARGB_8888);
        }

        Canvas canvas = new Canvas(result);
        Paint paint = new Paint();
        paint.setShader(new BitmapShader(source, BitmapShader.TileMode.CLAMP, BitmapShader.TileMode.CLAMP));
        paint.setAntiAlias(true);

        //四个圆角
        RectF rectF = new RectF(0f, 0f, source.getWidth(), source.getHeight());
        canvas.drawRoundRect(rectF, radius, radius, paint);

        //自定义画path实现顶部两个圆角
//        Path path = new Path();
//        path.reset();
//        int radius = 10;
//        //buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j] + (radius * 2), buffer.buffer[j + 1] + (radius * 2)
//        RectF rectFLeft = new RectF(0f, 0f, 0f + (radius * 2), 0f + (radius * 2));
//        path.moveTo(0f, 0f + radius);
//        path.arcTo(rectFLeft, 180, 90);
//        path.lineTo(source.getWidth() - radius, 0f);
//        path.moveTo(source.getWidth() - radius, 0f);
//        RectF rectFRight = new RectF(source.getWidth() - (radius * 2), 0f, source.getWidth(), 0f + (radius * 2));
//        path.arcTo(rectFRight, 270, 90);
//        path.lineTo(source.getWidth(), source.getHeight());
//        path.lineTo(0f, source.getHeight());
//        path.lineTo(0f, 0f + radius);
//        path.close();
//        canvas.drawPath(path, paint);

        return result;
    }

    @Override
    public void updateDiskCacheKey(@NonNull MessageDigest messageDigest) {

    }
}
